package com.tiyende.kash.loop.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import androidx.core.net.toUri
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lib.common.adapter.CommonOnItemChildClickListener
import com.lib.common.adapter.CommonRecyclerViewAdapter
import com.lib.common.adapter.CommonViewHolderHelper
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.common.CommonDialog
import com.tiyende.kash.loop.configs.TiyendeApiPath
import com.tiyende.kash.loop.configs.TiyendeApiUrl
import com.tiyende.kash.loop.configs.TiyendeConfigs
import com.tiyende.kash.loop.databinding.TiyendeDialogCustomerBinding
import com.tiyende.kash.loop.event.TiyendeEventPointHelper
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.request.IHttpCallback
import com.tiyende.kash.loop.utils.helper.TiyendeConfigsHelper
import com.tiyende.kash.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.kash.loop.utils.shared.TiyendeSharedKey
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/15 10:29
 * @Annotation：联系客服Dialog
 */
class TiyendeCustomerDialog(context: Context) : CommonDialog(context) {
    lateinit var binding: TiyendeDialogCustomerBinding
    private var callback: IDialogCallback? = null
    //事件备注
    private var eventRemark: String? = ""
    //产品名称
    private var pName = TiyendeConfigs.TIYENDE_APPNAME
    //产品Token
    private var pToken = TiyendeSharedHelper.queryTiyendeSharedString(TiyendeSharedKey.TIYENDE_TOKEN)
    //客服联系方式列表
    private var customerAdapter: CustomerItemAdapter? = null

    override fun getTiyendeRootView(): View {
        binding = TiyendeDialogCustomerBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initTiyendeView() {
        initCustomerListView()
    }

    override fun initTiyendeListener() {
        setOnClickListener(binding.customerClose)
        setOnClickListener(binding.customerChatOnline)
    }

    override fun loadTiyendeData() {
        //主产品
        if (this.pName == TiyendeConfigs.TIYENDE_APPNAME){
            val commonInfo = TiyendeSharedHelper.queryTiyendeSharedString(TiyendeSharedKey.TIYENDE_COMMON)
            if (commonInfo.isEmpty()){
                loadCustomerContactListAction()
                return
            }
            val data = JSONObject(commonInfo)
            setCustomerContactData(data)
        } else {
            loadCustomerContactListAction()
        }
    }

    override fun onTiyendeViewClick(v: View?) {
        dismiss()
        callback?.onClick(v)
    }

    /**
     * 事件备注
     */
    fun setCustomerEventRemark(remark: String?): TiyendeCustomerDialog{
        this.eventRemark = remark
        return this
    }

    /**
     * 对应的产品名称
     */
    fun setCustomerProductName(name: String): TiyendeCustomerDialog{
        if (name.isNotEmpty()){
            this.pName = name
        }
        return this
    }

    /**
     * 对应的产品Token
     */
    fun setCustomerProductToken(token: String): TiyendeCustomerDialog{
        if (pToken.isNotEmpty()){
            this.pToken = token
        }
        return this
    }

    /**
     * 设置监听回调
     */
    fun setCustomerClickCallback(callback: IDialogCallback): TiyendeCustomerDialog{
        this.callback = callback
        return this
    }

    fun setCustomerCancelable(flag: Boolean): TiyendeCustomerDialog{
        setCancelable(flag)
        return this
    }

    fun setCustomerCanceledOnTouchOutside(flag: Boolean): TiyendeCustomerDialog{
        setCanceledOnTouchOutside(flag)
        return this
    }

    /**
     * 初始化Tab列表
     */
    private fun initCustomerListView() {
        binding.customerTime.visibility = View.GONE
        binding.customerListView.visibility = View.GONE
        binding.customerListView.layoutManager = LinearLayoutManager(context)
        customerAdapter = CustomerItemAdapter(binding.customerListView)
        binding.customerListView.adapter = customerAdapter
        binding.customerListView.itemAnimator = DefaultItemAnimator()
        customerAdapter?.setOnItemChildClickListener(CommonOnItemChildClickListener { _, childView, position ->
            val item = customerAdapter?.getItem(position)
            if (childView.id == R.id.btnCustomer) {
                item?.let {
                    when (it.optString("type")) {
                        "MOBILE" -> {//电话
                            onCustomerMobileCallAction(it)
                        }

                        else -> {//邮箱
                        }
                    }
                }
            }
        })
    }

    /**
     * 获取联系方式列表
     */
    private fun loadCustomerContactListAction(){
        val params = JSONObject().apply {
            put("path",TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_APP_INFO_PATH)
            put("product",pName)
            put("token",pToken)
        }
        val httpUrl = TiyendeApiUrl.getTiyendeHttpUrl()
        doPostAction(httpUrl, params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        //保存所有数据
                        if (obj != null) {
                            setCustomerContactData(obj)
                        }
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                showTiyendeToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取联系方式列表
     */
    @SuppressLint("SetTextI18n")
    private fun setCustomerContactData(data: JSONObject){
        binding.customerTime.visibility = View.VISIBLE
        binding.customerListView.visibility = View.VISIBLE
        val contactList = arrayListOf<JSONObject>()
        val customize = data.optJSONObject("customize")
        if (customize != null){
            val mobileStr = customize.optString("mobile","")
            if (mobileStr.isNotEmpty()){
                val mobileList = mobileStr.split(",")
                for (i in mobileList.indices){
                    val obj = JSONObject()
                    obj.put("type","MOBILE")
                    obj.put("value", mobileList[i])
                    contactList.add(obj)
                }
            }
            val emailStr = customize.optString("email","")
            if (emailStr.isNotEmpty()){
                val emailList = emailStr.split(",")
                for (i in emailList.indices){
                    val obj = JSONObject()
                    obj.put("type","EMAIL")
                    obj.put("value", emailList[i])
                    contactList.add(obj)
                }
            }
        }
        customerAdapter?.data = contactList

        //工作时间
        //客服配置里没有配置工作时间，取主产品的工作时间展示
        var workDate = "Monday to Sunday"
        var workTime = "9:30am to 19:30pm."
        val customData = customize?.optJSONObject("customData")
        customData?.let {
            if (!it.has("workDate") || !it.has("workTime")){
                val commonCustomData = TiyendeConfigsHelper.queryTiyendeCustomData()
                if (commonCustomData != null) {
                    it.put("workDate",commonCustomData.optString("workDate"))
                    it.put("workTime",commonCustomData.optString("workTime"))
                    it.put("workDate_hi",commonCustomData.optString("workDate_hi"))
                    it.put("workTime_hi",commonCustomData.optString("workTime_hi"))
                }
            }
            if (!it.has("workDate_hi") || !it.has("workTime_hi")){
                val commonCustomData = TiyendeConfigsHelper.queryTiyendeCustomData()
                if (commonCustomData != null) {
                    it.put("workDate_hi",commonCustomData.optString("workDate_hi"))
                    it.put("workTime_hi",commonCustomData.optString("workTime_hi"))
                }
            }
            workDate = if (TiyendeConfigs.isHindi()){it.optString("workDate_hi")} else { it.optString("workDate") }
            workTime = if (TiyendeConfigs.isHindi()){it.optString("workTime_hi")} else { it.optString("workTime") }
        }
        binding.customerTime.text = "$workDate,$workTime"
    }

    /**
     * 拨号
     */
    private fun onCustomerMobileCallAction(item: JSONObject){
        val type = item.optString("type")
        TiyendeEventPointHelper.addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_KEFU_DIAL,type + "：" + item.optString("value"))
        val callIntent = Intent(Intent.ACTION_DIAL)
        callIntent.data = "tel:${item.optString("value")}".toUri()
        context.startActivity(callIntent)
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
    }

    class CustomerItemAdapter(recyclerView: RecyclerView?) : CommonRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.tiyende_dialog_customer_item) {
        override fun setItemChildListener(helper: CommonViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.btnCustomer) //拨号、复制
        }

        override fun fillData(helper: CommonViewHolderHelper, position: Int, model: JSONObject) {
            helper.setText(R.id.textCustomerValue,model.optString("value"))
            val imgCustomerFun = helper.getImageView(R.id.imgCustomerFun)
            when(model.optString("type")){
                "MOBILE" -> {//电话
                    helper.setText(R.id.textCustomerTitle,String.format(mContext.getString(R.string.tiyende_dialog_customer_mobile_title),"${position +1}"))
                    helper.setText(R.id.textCustomerFun,mContext.getString(R.string.tiyende_dialog_customer_mobile_dial))
                    imgCustomerFun.setImageResource(R.mipmap.tiyende_customer_mobile_call)
                    helper.setVisibility(R.id.btnCustomer,View.VISIBLE)
                }
                else -> {//邮箱
                    helper.setText(R.id.textCustomerTitle,mContext.getString(R.string.tiyende_dialog_customer_email_title))
                    helper.setText(R.id.textCustomerFun,mContext.getString(R.string.tiyende_dialog_customer_email_copy))
                    imgCustomerFun.setImageResource(R.mipmap.tiyende_customer_email_copy)
                    helper.setVisibility(R.id.btnCustomer,View.INVISIBLE)
                }
            }
        }
    }

    override fun onStart() {
        super.onStart()
        TiyendeEventPointHelper.addEventPointRequestAction(TiyendeEventPointType.DIALOG.TIYENDE_DIALOG_CUSTOMER_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        TiyendeEventPointHelper.addEventPointRequestAction(TiyendeEventPointType.DIALOG.TIYENDE_DIALOG_CUSTOMER_DISMISS,eventRemark)
    }
}